import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent, STData } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { map } from 'rxjs/operators';
import { of } from 'rxjs';
import { SearchDrawerService, ShipperBaseService } from '@shared';
import { Router } from '@angular/router';
import { InsuranceManagementService } from '../../services/insurance-management.service';
import { BasicTableComponent } from 'src/app/routes/commom';

@Component({
  selector: 'app-insurance-management-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class insuranceManagementListComponent extends BasicTableComponent implements OnInit {
  uiView: SFUISchema = {};
  schemaView: SFSchema = {};
  auditMany = false;
  isVisibleView = false;
  isVisibleEvaluate = false;
  isVisible = false;
  @ViewChild('stFloat') private readonly stFloat!: STComponent;
  @ViewChild('stFloatView') private readonly stFloatView!: STComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  columns: STColumn[] = [];
  columnsFloat: STColumn[] = [];
  columnsFloatView: STColumn[] = [];
  demoValue: any;
  resourceStatus: any;
  datass: any = [
    {
      one: '1',
      two: '1',
      three: '1',
      id: 1
    },
    {
      one: '2',
      two: '2',
      three: '2',
      id: 2
    }
  ];
  tabs = {
    totalCount: 0,
    receivedQuantity: 0,
    stayQuantity: 0,
    GoingQuantity: 0,
    cancelQuantity: 0
  };
  constructor(
    public service: InsuranceManagementService,
    private modal: NzModalService,
    public shipperservice: ShipperBaseService,
    private router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus) {
      a.insureStatus = this.resourceStatus;
    }
    const params: any = Object.assign({}, this.sf?.value || {});
    delete params._$expand;
    return {
      ...a,
      ...params,
      createTime: {
        start: this.sf?.value?.createTime?.[0] || '',
        end: this.sf?.value?.createTime?.[1] || ''
      },
      recordTime: {
        start: this.sf?.value?.recordTime?.[0] || '',
        end: this.sf?.value?.recordTime?.[1] || ''
      },
      insureTime: {
        start: this.sf?.value?.insureTime?.[0] || '',
        end: this.sf?.value?.insureTime?.[1] || ''
      }
    };
  }
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  search() {
    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  getGoodsSourceStatistical() {
    this.tabs = {
      totalCount: 0,
      receivedQuantity: 0,
      stayQuantity: 0,
      GoingQuantity: 0,
      cancelQuantity: 0
    };
    const params: any = Object.assign({}, this.reqParams || {});
    delete params.insureStatus;
    this.service.request(this.service.$api_listStatisticalStatus, params).subscribe((res: any) => {
      if (res) {
        let totalCount = 0;
        res.forEach((element: any) => {
          if (element.insureStatusLabel === '待投保') {
            this.tabs.receivedQuantity = element.quantity;
          } else if (element.insureStatusLabel === '已投保') {
            this.tabs.stayQuantity = element.quantity;
          } else if (element.insureStatusLabel === '投保失败') {
            this.tabs.GoingQuantity = element.quantity;
          } else if (element.insureStatusLabel === '已取消') {
            this.tabs.cancelQuantity = element.quantity;
          }
          totalCount += element.quantity;
        });
        this.tabs.totalCount = totalCount;
      }
    });
  }
  selectChange(e: number) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
  ngOnInit(): void {
    this.getGoodsSourceStatistical();
    this.initSF();
    this.initST();
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        insureCode: {
          type: 'string',
          title: '投保编号'
        },
        billCode: {
          type: 'string',
          title: '订单号'
        },
        resourceCode: {
          type: 'string',
          title: '货源编号'
        },
        policyNo: {
          type: 'string',
          title: '保单号',
          ui: {}
        },
        insureType: {
          title: '类型',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'insure:type' },
            containsAllLabel: true
          } as SFSelectWidgetSchema
        },
        startAddress: {
          type: 'string',
          title: '始发地',
          ui: {}
        },
        endAddress: {
          type: 'string',
          title: '目的地',
          ui: {}
        },
        shipperAppUserId: {
          type: 'string',
          title: '货主',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_enterpriceList, { enterpriseName: str })
                  .pipe(map((res: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.id } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            change: (q: any) => {
              this.getRegionCode(q);
            }
          } as SFSelectWidgetSchema
        },
        enterpriseProjectId: {
          type: 'string',
          title: '所属项目',
          ui: {
            widget: 'select',
            placeholder: '请先选择货主'
          } as SFSelectWidgetSchema
        },

        driverName: {
          title: '承运司机',
          type: 'string',
          ui: {}
        },
        carNo: {
          title: '车牌号',
          type: 'string',
          ui: {}
        },
        insureStatus: {
          title: '投保状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'insure:status' },
            containsAllLabel: true
          } as SFSelectWidgetSchema
        },
        insureRefundStatus: {
          title: '退款状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'insure:refund:status' },
            containsAllLable: true
          } as SFSelectWidgetSchema
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        },
        insureTime: {
          title: '投保时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true
          } as SFDateWidgetSchema
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true
          } as SFDateWidgetSchema
        },
        recordTime: {
          title: '录单时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true
          } as SFDateWidgetSchema
        }
      },
      type: 'object'
    };
  }
  // 获取城市列表
  getRegionCode(regionCode: any) {
    console.log(regionCode);
    return this.service
      .request(this.service.$api_get_enterprise_project, { id: regionCode })
      .pipe(
        map(res =>
          res.map((item: any) => ({
            label: item.projectName,
            value: item.id
          }))
        )
      )
      .subscribe(res => {
        this.sf.getProperty('/enterpriseProjectId')!.schema.enum = res;
        this.sf.getProperty('/enterpriseProjectId')!.widget.reset(res);
        // if (this.enterpriseProjectIds) {
        //   this.sf1.setValue('/enterpriseProjectId', this.enterpriseProjectIds);
        // }
      });
  }
  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      {
        title: '投保编号',
        width: '180px',
        fixed: 'left',
        className: 'text-left',
        render: 'insureCode'
      },
      {
        title: '保单号',
        width: '250px',
        className: 'text-right',
        index: 'policyNo'
      },
      { title: '类型', index: 'insureTypeLabel', width: '220px', className: 'text-left' },
      { title: '始发地', index: 'startAddress', width: '220px', className: 'text-left' },
      { title: '目的地', index: 'endAddress', width: '220px', className: 'text-left' },
      { title: '距离', render: 'distance', width: '180px', className: 'text-left' },
      { title: '保额（元）', render: 'insureAmount', width: '180px', className: 'text-right' },
      { title: '保费（元）', render: 'premium', width: '180px', className: 'text-right' },
      // {
      //   title: '实际保费（元）',
      //   className: 'text-right',
      //   width: '180px',
      //   render: 'practicalPremium'
      // },
      {
        title: '货物信息',
        className: 'text-left',
        width: '250px',
        render: 'goodsName'
      },
      {
        title: '承运司机',
        className: 'text-right',
        width: '250px',
        render: 'driverName'
      },
      {
        title: '关联订单号',
        className: 'text-right',
        render: 'goodsNumber',
        width: '180px'
      },
      {
        title: '货源编号',
        className: 'text-right',
        render: 'resourceCode',
        width: '150px'
      },
      {
        title: '网络货运人',
        className: 'text-left',
        width: '250px',
        index: 'enterpriseInfoName'
      },
      {
        title: '货主',
        className: 'text-left',
        width: '250px',
        index: 'shipperAppUserName'
      },
      {
        title: '所属项目',
        width: '250px',
        className: 'text-left',
        index: 'enterpriseProjectName'
      },
      {
        title: '投保时间',
        width: '180px',
        className: 'text-left',
        index: 'insureTime'
      },
      {
        title: '生效时间',
        width: '180px',
        className: 'text-left',
        index: 'effectTime'
      },
      {
        title: '录单时间',
        width: '180px',
        className: 'text-left',
        index: 'recordTime'
      },
      {
        title: '创建时间',
        width: '180px',
        className: 'text-left',
        index: 'createTime'
      },
      {
        title: '失败原因',
        width: '180px',
        className: 'text-left',
        render: 'processMessage'
        // processResult=2
      },
      {
        title: '退款状态',
        width: '180px',
        className: 'text-left',
        index: 'insureRefundStatusLabel'
        // processResult=2
      },
      {
        title: '操作',
        fixed: 'right',
        width: '110px',
        className: 'text-center',
        buttons: [
          {
            text: '查看保单',
            click: _record => this.showImg(_record),
            iif: item => item.insureStatus == '2'
            // acl: { ability: ['VEHICLE-LIST-view'] },
            // iif: item =>
            //   item.billStatus == '4' || item.billStatus == '5' || item.billStatus == '2' || item.billStatus == '3' || item.billStatus == '1'
          },
          {
            text: '退保费',
            click: _record => this.retreatPrice(_record),
            iif: item => item.insureStatus == '2'
            // acl: { ability: ['VEHICLE-LIST-view'] },
          }
        ]
      }
    ];
  }
  showImg(_record: any) {
    // var newUrl=_record.policyUrl.replace('http','https')
    // console.log(newUrl);

    // window.open(newUrl,'_self');
    window.open(`${_record.newPolicyUrl}`);
    // this.service.downloadFile(`${_record.newPolicyUrl}`)

    // const params = {
    //   imgList: [_record.policyUrl],
    //   index: 0
    // };
    // this.modal.create({ nzContent: ImageViewComponent, nzComponentParams: { params } });
  }
  tabChange(item: any) {}

  // 退保费
  retreatPrice(value: any) {
    this.modal.warning({
      nzTitle: '确认退还保费吗？',
      nzClosable: true,
      nzContent: '退还后不可撤销，请谨慎操作！',
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_get_addINPBillRefundApplication, { id: value.id }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('删除菜单成功');
          }
        });
      }
    });
  }
  // 再次投保
  retreatNext(value: any) {
    this.modal.warning({
      nzTitle: '确认再次投保吗？',
      nzClosable: true,
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_del_many, [value.id]).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('删除菜单成功');
          }
        });
      }
    });
  }
  // 保险配置
  changeOrder() {
    this.router.navigate(['/insurance-management/list-set']);
  }
  exprot() {
    this.service.downloadFile(this.service.$api_get_asyncExport, { ...this.reqParams, pageSize: -1 });
  }
}
